package co.gov.medellin.sdep.sisdep.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

import co.gov.medellin.sdep.sisdep.model.EstConcepto;

public class EstConceptoDAOImpl extends JdbcDaoSupport implements IEstConceptoDAO {

    private InsertOperation insertOperation;
    
    private InsertDetalleOperation insertDetalleOperation;

    private UpdateOperation updateOperation;
    
    private UpdateDetalleOperation updateDetalleOperation;

    private DeleteOperation deleteOperation;

    private DeleteByPrimaryKey deleteByPrimaryKey;

    private FindByPrimaryKeyQuery findByPrimaryKeyQuery;

    private FindByCriteriaQuery findByCriteriaQuery;

    private FindAllQuery findAllQuery;
    
    private FindByIdEstudioQuery findByIdEstudioQuery;
    
    private FindConceptoDetalleQuery findConceptoDetalleQuery;
    
    private LitaClasificacionSocioEconomico findClasificacionQuery;

    private FindByActiveStateQuery findByActiveStateQuery;

	private static final String SELECT = "SELECT * FROM GES_EST_CONCEPTO_T ";
	private static final String WHERE = " WHERE ";
	private static final String PARAMETER = " ?, ";

    public void delete(EstConcepto estConcepto) {
		deleteOperation.execute( estConcepto  );
	}

	public void deleteByPrimaryKey(long id) {
		deleteByPrimaryKey.execute(id);
	}

	public EstConcepto findByPrimaryKey(long login) {
		return findByPrimaryKeyQuery.runQuery(login);
	}

	public void insert(EstConcepto estConcepto) {
		insertOperation.execute( estConcepto );
	}
	
	public void insertDetalle(EstConcepto estConcepto) {
		insertDetalleOperation.execute( estConcepto );
	}

	public void update(EstConcepto estConcepto) {
		updateOperation.execute( estConcepto );
	}
	
	public void updateDetalle(EstConcepto estConcepto) {
		updateDetalleOperation.execute( estConcepto );
	}

	public EstConcepto findByCriteria(EstConcepto  estConcepto) {
		return findByCriteriaQuery.runQuery(estConcepto);
	}

	public List load() {
		return findAllQuery.runQuery();
	}
	
	public List loadByIdEstudio(EstConcepto estConcepto) {
		return findByIdEstudioQuery.runQuery(estConcepto);
	}
	
	public List loadDetalleConcepto(EstConcepto estConcepto) {
		return findConceptoDetalleQuery.runQuery(estConcepto);
	}

	public List loadClasificacion() {
		return findClasificacionQuery.runQuery();
	}
	
	public EstConcepto findByActiveState(EstConcepto  estConcepto) {
		return findByActiveStateQuery.runQuery(estConcepto);
	}

	public void initDao() {
    	insertOperation   = new InsertOperation( getDataSource() );
    	insertDetalleOperation   = new InsertDetalleOperation( getDataSource() );
    	updateOperation = new UpdateOperation(  getDataSource() );
    	updateDetalleOperation = new UpdateDetalleOperation(  getDataSource() );
  //  	deleteOperation = new DeleteOperation(  getDataSource() );
  //  	deleteByPrimaryKey = new DeleteByPrimaryKey( getDataSource());
  //  	findByPrimaryKeyQuery   = new FindByPrimaryKeyQuery(  getDataSource() );
  //  	findByCriteriaQuery = new FindByCriteriaQuery(  getDataSource() );
    	findAllQuery = new FindAllQuery( getDataSource() );
    	findByIdEstudioQuery = new FindByIdEstudioQuery( getDataSource() );
    	findClasificacionQuery = new LitaClasificacionSocioEconomico(getDataSource());
    	findConceptoDetalleQuery = new FindConceptoDetalleQuery(getDataSource());
  //  	findByActiveStateQuery = new FindByActiveStateQuery( getDataSource() );
    }

    // ------------- SaveOperation ---------------------------------------
	class InsertOperation extends SqlUpdate	{
		private static final String sql = "INSERT INTO GES_EST_CONCEPTO_T ("
				  + " ID, "
				  + " ID_EST_SOCIO_ECONOMICO, "
				  + " ID_ESTADO_SOCIO_ECO, "
				  + " PUNTAJE_TOTAL, "
				  + " ESTADO, "
				  + " USUARIO_CREA, "
				  + " FECHA_CREA"
				  + ") VALUES ("
			  	  + " GES_EST_CONCEPTO_SEC.nextVal, "
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "SYSDATE"
				  + ")";
		public  InsertOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));			
			compile();
		}
		public void execute(EstConcepto estConcepto) {
			InsertOperation.this.update( new Object[]{				
				estConcepto.getIdEstSocioEconomico(),
				estConcepto.getIdEstadoSocioEco(),
				estConcepto.getPuntajeTotal(),
				estConcepto.getEstado(),
				estConcepto.getUsuarioCrea()				
				});
		}
    }

    // ------------- SaveOperation ---------------------------------------
	class InsertDetalleOperation extends SqlUpdate	{
		private static final String sql = "INSERT INTO GES_EST_CONCEPTO_DET_T ("
				  + " ID, "
				  + " ID_EST_CONCEPTO, "
				  + " ID_EST_CONCEPTO_CARAC, "
				  + " APLICA, "
				  + " VALOR_PESO, "
				  + " USUARIO_CREA, "
				  + " FECHA_CREA"
				  + ") VALUES ("
			  	  + " GES_EST_CONCEPTO_DET_SEC.nextVal, "
				  + "(SELECT ID FROM GES_EST_CONCEPTO_T WHERE ID_EST_SOCIO_ECONOMICO = ?), "
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "SYSDATE"
				  + ")";
		public  InsertDetalleOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));			
			compile();
		}
		public void execute(EstConcepto estConcepto) {
			InsertDetalleOperation.this.update( new Object[]{				
				estConcepto.getIdEstSocioEconomico(),
				estConcepto.getIdCaracteristica(),
				estConcepto.getAplica(),
				estConcepto.getPeso(),
				estConcepto.getUsuarioCrea()				
				});
		}
    }	
    // ------------- UpdateOperation -------------------------------------
    class UpdateOperation extends SqlUpdate	{
    	private static final String sql = "UPDATE GES_EST_CONCEPTO_T SET "					  
					  + " ID_EST_SOCIO_ECONOMICO = ? ,"
					  + " ID_ESTADO_SOCIO_ECO = ? ,"
					  + " PUNTAJE_TOTAL = ? ,"
					  + " ESTADO = ? ,"					  
					  + " USUARIO_MODIFICA = ? ,"
					  + " FECHA_MODIFICA = SYSDATE"
				  	  + WHERE
				  	  + " ID = ? ";
		public  UpdateOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));			
			compile();
		}
		public void execute(EstConcepto estConcepto) {
			UpdateOperation.this.update( new Object[]{				
				estConcepto.getIdEstSocioEconomico(),
				estConcepto.getIdEstadoSocioEco(),
				estConcepto.getPuntajeTotal(),
				estConcepto.getEstado(),			
				estConcepto.getUsuarioModifica(),				
				estConcepto.getId()
				});
		}
    }
    
    // ------------- UpdateDetalleOperation -------------------------------------
    class UpdateDetalleOperation extends SqlUpdate	{
    	private static final String sql = "UPDATE GES_EST_CONCEPTO_DET_T SET "					  
					  + " ID_EST_CONCEPTO = ? ,"
					  + " ID_EST_CONCEPTO_CARAC = ? ,"
					  + " APLICA = ? ,"
					  + " VALOR_PESO = ? ,"					  
					  + " USUARIO_MODIFICA = ? ,"
					  + " FECHA_MODIFICA = SYSDATE"
				  	  + WHERE
				  	  + " ID = ? ";
		public  UpdateDetalleOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));			
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));			
			compile();
		}
		public void execute(EstConcepto estConcepto) {
			UpdateDetalleOperation.this.update( new Object[]{				
				estConcepto.getId(),
				estConcepto.getIdCaracteristica(),
				estConcepto.getAplica(),
				estConcepto.getPeso(),
				estConcepto.getUsuarioModifica(),				
				estConcepto.getIdDetalle()
				});
		}
    }
    // ------------- DeleteOperation -------------------------------------
    class DeleteOperation extends SqlUpdate	{
		private static final String sql = "DELETE FROM GES_EST_CONCEPTO_T "
										+ WHERE + "1=1";
		public DeleteOperation(DataSource ds) {
			super(ds,sql);
			compile();
		}
		public void execute(EstConcepto estConcepto) {
			this.update( new Object[]{
			});
		}
	}

    // ------------- DeleteByPrimaryKey ----------------------------------
    class DeleteByPrimaryKey extends SqlUpdate	{
		private static final String sql = "DELETE FROM GES_EST_CONCEPTO_T "
										+ WHERE + "1=1";
		public DeleteByPrimaryKey(DataSource ds) {
			super(ds,sql);
			compile();
		}	
		public void execute(long id) {
			this.update( new Object[]{
			});
		}	
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class BaseQueryOperation extends MappingSqlQuery {
		public BaseQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			EstConcepto estConcepto = new EstConcepto();
				estConcepto.setId(new Long(rs.getLong("ID")));
				estConcepto.setIdEstSocioEconomico(new Long(rs.getLong("ID_EST_SOCIO_ECONOMICO")));
				estConcepto.setIdEstadoSocioEco(new Long(rs.getLong("ID_ESTADO_SOCIO_ECO")));
				estConcepto.setPuntajeTotal(new Long(rs.getLong("PUNTAJE_TOTAL")));
				estConcepto.setPuntajeTotalStr(rs.getString("PUNTAJE_TOTAL"));
				estConcepto.setEstado(rs.getString("ESTADO"));
				estConcepto.setUsuarioCrea(rs.getString("USUARIO_CREA"));
				estConcepto.setFechaCrea(rs.getDate("FECHA_CREA"));		
				estConcepto.setUsuarioModifica(rs.getString("USUARIO_MODIFICA"));
				estConcepto.setFechaModifica(rs.getDate("FECHA_MODIFICA"));		
			return estConcepto;
		}
    }
	
    // ---- ConceptoDetalleQueryOperation for Mapping ResultSet values --------------
	abstract class ConceptoDetalleQueryOperation extends MappingSqlQuery {
		public ConceptoDetalleQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			EstConcepto estConcepto = new EstConcepto();			
			    estConcepto.setIdDetalle(new Long(rs.getLong("ID")));
				estConcepto.setId(new Long(rs.getLong("ID_EST_CONCEPTO")));				
				estConcepto.setIdCaracteristica(new Long(rs.getLong("ID_EST_CONCEPTO_CARAC")));
				estConcepto.setAplica(rs.getString("APLICA"));
				estConcepto.setPeso(new Long(rs.getLong("VALOR_PESO")));
				estConcepto.setPesoStr(rs.getString("VALOR_PESO"));
				estConcepto.setUsuarioCreaDetalle(rs.getString("USUARIO_CREA"));
				estConcepto.setFechaCreaDetalle(rs.getDate("FECHA_CREA"));
				estConcepto.setUsuarioModificaDetalle(rs.getString("USUARIO_MODIFICA"));
				estConcepto.setFechaModificaDetalle(rs.getDate("FECHA_MODIFICA"));
				estConcepto.setIdVariable(new Long(rs.getLong("ID_VAR")));
				estConcepto.setNombreVariable(rs.getString("VAR"));
				estConcepto.setCodigo(rs.getString("CODIGO"));
				estConcepto.setNombreCaracteristica(rs.getString("NOMBRE_CARACTERISTICA"));
				estConcepto.setPesoMax(new Long(rs.getLong("PESO_MAX")));
				estConcepto.setPesoMaxStr(rs.getString("PESO_MAX"));
				
				return estConcepto;
		}
    }
	
	// ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class ClasificacionSocioEconomicaQueryOperation extends MappingSqlQuery {
		public ClasificacionSocioEconomicaQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			EstConcepto estConcepto = new EstConcepto();			
			    estConcepto.setIdVariable(new Long(rs.getLong("ID_VAR")));
				estConcepto.setNombreVariable(rs.getString("VAR"));				
				estConcepto.setIdCaracteristica(new Long(rs.getLong("ID")));
				estConcepto.setCodigo(rs.getString("CODIGO"));
				estConcepto.setNombreCaracteristica(rs.getString("NOMBRE"));
				estConcepto.setPesoMax(new Long(rs.getLong("PESO")));
				estConcepto.setAplica("");
				return estConcepto;
		}
    }

    // ------------- FindByPrimaryKeyQuery -------------------------------
    class FindByPrimaryKeyQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + "1=1";
    	public FindByPrimaryKeyQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public EstConcepto runQuery(long id) {
			List result =  execute( new Object[]{new Long(id)});
			if ( result.size() > 0 ) {
        		return (EstConcepto) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByCriteriaQuery ---------------------------------    
    class FindByCriteriaQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
			//For required criteria elements uncomment required values
			  	  	  					//+ " AND ID = ? "
			  	  	  					//+ " AND ID_EST_SOCIO_ECONOMICO = ? "
			  	  	  					//+ " AND ID_ESTADO_SOCIO_ECO = ? "
			  	  	  					//+ " AND PUNTAJE_TOTAL = ? "
			  	  	  					//+ " AND ESTADO = ? "
			  	  	  					//+ " AND USUARIO_CREA = ? "
			  	  	  					//+ " AND FECHA_CREA = ? "
			  	  	  					//+ " AND USUARIO_MODIFICA = ? "
			  	  	  					//+ " AND FECHA_MODIFICA = ? "
										//+ "";
    	public FindByCriteriaQuery(DataSource ds) {
    		super(ds,sql);
    		//For required criteria elements uncomment required values
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			compile();
    	}
    	public EstConcepto runQuery(EstConcepto estConcepto) {
			List result =  execute( new Object[]{
			//For required criteria elements uncomment required values
				//estConcepto.getId(),
				//estConcepto.getIdEstSocioEconomico(),
				//estConcepto.getIdEstadoSocioEco(),
				//estConcepto.getPuntajeTotal(),
				//estConcepto.getEstado(),
				//estConcepto.getUsuarioCrea(),
				//estConcepto.getFechaCrea(),
				//estConcepto.getUsuarioModifica(),
				//estConcepto.getFechaModifica(),
				});
			if ( result.size() > 0 ) {
        		return (EstConcepto) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindAllQuery ----------------------------------------    
    class FindAllQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
    	public FindAllQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public List runQuery() {
			List result =  execute();
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }
    
    // ------------- FindByIdEstudioQuery ----------------------------------------    
    class FindByIdEstudioQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + "ID_EST_SOCIO_ECONOMICO=? ";
    	public FindByIdEstudioQuery(DataSource ds) {
    		super(ds,sql);
    		declareParameter( new SqlParameter(Types.INTEGER) );
			compile();
    	}
    	public List runQuery(EstConcepto estConcepto) {
    		List result = execute( new Object[]{
					estConcepto.getIdEstSocioEconomico()
			});
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }
    
    
    // ------------- FindConceptoDetalleQuery ----------------------------------------    
    class FindConceptoDetalleQuery extends ConceptoDetalleQueryOperation {
		private static final String sql = "SELECT DET.*,MAE.ID_VALOR_TIPO AS ID_VAR, MAE.VRT_NOMBRE AS VAR, CARAC.CODIGO," 
										+ " CARAC.NOMBRE AS NOMBRE_CARACTERISTICA, CARAC.PESO AS PESO_MAX "
										+ " FROM GES_EST_CONCEPTO_DET_T DET INNER JOIN "
										+ " GES_EST_CONCEPTO_CARAC_T CARAC ON DET.ID_EST_CONCEPTO_CARAC = CARAC.ID INNER JOIN "
										+ " ADM_VALOR_TIPO_MAESTRA_T MAE ON CARAC.ID_VAR_SOCIOECONOMICA=MAE.ID_VALOR_TIPO "
										+ " WHERE DET.ID_EST_CONCEPTO=? "
										+ " ORDER BY MAE.ID_VALOR_TIPO,ORDEN";
    	public FindConceptoDetalleQuery(DataSource ds) {
    		super(ds,sql);
    		declareParameter( new SqlParameter(Types.INTEGER) );
			compile();
    	}
    	public List runQuery(EstConcepto estConcepto) {
			List result = execute( new Object[]{
					estConcepto.getId()
			});
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }    

    // ------------- FindByActiveStateQuery  -----------------------------
    class LitaClasificacionSocioEconomico extends ClasificacionSocioEconomicaQueryOperation {
		private static final String sql = " SELECT  MAE.ID_VALOR_TIPO AS ID_VAR,MAE.VRT_NOMBRE AS VAR,CON.ID,CON.CODIGO,CON.NOMBRE,CON.PESO " 
										+ " FROM GES_EST_CONCEPTO_CARAC_T  CON INNER JOIN "
										+ " ADM_VALOR_TIPO_MAESTRA_T MAE ON CON.ID_VAR_SOCIOECONOMICA=MAE.ID_VALOR_TIPO"
										+ "  ORDER BY ID_VALOR_TIPO,ORDEN";	
    	public LitaClasificacionSocioEconomico(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public List runQuery() {
			List result =   execute();
			if ( result.size() > 0 ) {
				return  result;
        	} else {
        		return null;
        	}
    	}
    }
    
    // ------------- FindByActiveStateQuery  -----------------------------
    class FindByActiveStateQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + "1=1";
    	public FindByActiveStateQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public EstConcepto runQuery(EstConcepto estConcepto) {
			List result =  execute( new Object[]{
			});
			if ( result.size() > 0 ) {
        		return (EstConcepto) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

}
